import 'dart:io';
import 'dart:convert';
import 'dart:typed_data';
import 'package:path_provider/path_provider.dart';
import 'package:encrypt/encrypt.dart' as encrypt;
import 'package:crypto/crypto.dart';

class SecureFileStorage {
  static const _keyEnvVar = 'ENCRYPTION_KEY';
  static const _ivEnvVar = 'ENCRYPTION_IV';
  
  static Future<String> get _storagePath async {
    final directory = await getApplicationSupportDirectory();
    return '${directory.path}/secure_storage.dat';
  }
  
  static encrypt.Encrypter _getEncrypter() {
    // 从环境变量获取密钥和IV
    final key = String.fromEnvironment(_keyEnvVar, 
        defaultValue: 'default32bytesKeyForDevelopmentOnly');
    final iv = String.fromEnvironment(_ivEnvVar, 
        defaultValue: '16bytesIVDefault');
    
    // 确保密钥是32字节
    final keyBytes = sha256.convert(utf8.encode(key)).bytes;
    final ivBytes = iv.padRight(16).substring(0, 16).codeUnits;
    
    return encrypt.Encrypter(encrypt.AES(
      encrypt.Key(Uint8List.fromList(keyBytes)),
    ));
  }
  
  static Future<void> saveCredentials(String username, String password) async {
    final path = await _storagePath;
    final file = File(path);
    
    final encrypter = _getEncrypter();
    final iv = encrypt.IV.fromLength(16);
    
    final encryptedUsername = encrypter.encrypt(username, iv: iv);
    final encryptedPassword = encrypter.encrypt(password, iv: iv);
    
    final data = {
      'u': encryptedUsername.base64,
      'p': encryptedPassword.base64,
      'iv': iv.base64,
    };
    
    File saveFile = await file.writeAsString(json.encode(data));
    print('saveFile---:$saveFile');
  }
  
  static Future<Map<String, String?>> getCredentials() async {
    final path = await _storagePath;
    final file = File(path);
    
    if (!await file.exists()) return {'username': null, 'password': null};
    
    try {
      final contents = await file.readAsString();
      final data = json.decode(contents) as Map<String, dynamic>;
      
      final encrypter = _getEncrypter();
      final iv = encrypt.IV.fromBase64(data['iv']);
      
      final username = encrypter.decrypt64(data['u'], iv: iv);
      final password = encrypter.decrypt64(data['p'], iv: iv);
      
      print('读取凭证：username=$username, password=$password'); // 添加
      return {'username': username, 'password': password};
    } catch (e) {
      print('读取安全存储失败: $e');
      await file.delete(); // 删除损坏的文件
      return {'username': null, 'password': null};
    }
  }
  
  static Future<void> clearCredentials() async {
    final path = await _storagePath;
    final file = File(path);
    if (await file.exists()) {
      await file.delete();
    }
  }
  
  static Future<void> generateKey() async {
    final key = encrypt.Key.fromSecureRandom(32);
    final iv = encrypt.IV.fromSecureRandom(16);
    
    print('ENCRYPTION_KEY=${key.base64}');
    print('ENCRYPTION_IV=${iv.base64}');
  }
}